import socket


'''凯撒密码加密'''
def encrypt(text, shift):
    result = ""
    for char in text:
        if char.isalpha():
            start = ord('A') if char.isupper() else ord('a')
            result += chr((ord(char) - start + shift) % 26 + start)
        else:
            result += char
    return result


'''凯撒密码解密'''
def decrypt(text, shift):
    return encrypt(text, -shift)


''' 新建服务端 socket'''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('192.168.190.2', 9999)
'''绑定'''
server_socket.bind(address)
'''监听'''
server_socket.listen(5)
'''接受'''
client_socket, address = server_socket.accept()
print("我们收到了{}的链接".format(address))

shift = 3
while True:
    encrypted_data = client_socket.recv(1024).decode()
    if not encrypted_data:
        break
    decrypted_data = decrypt(encrypted_data, shift)
    print("slave wk 说：{}".format(decrypted_data))

    try:
        with open('output.txt', 'a') as file:
            file.write(decrypted_data + '\n')
        print("收到的内容已保存到 output.txt。")
    except Exception as e:
        print(f"保存文件时出错: {e}")

    message = input("master zk 回应：")
    encrypted_message = encrypt(message, shift)
    client_socket.send(encrypted_message.encode())

'''关闭连接'''
client_socket.close()
server_socket.close()